package com.wangshouyu.mp.micro.session;

import com.google.gson.Gson;
import com.wangshouyu.mp.micro.base.constant.UrlConstant;
import com.wangshouyu.mp.micro.base.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;

/**
 * @author 王守钰
 * @description 小程序session工具
 * @date 2020/8/19 9:19
 */
public class MicroSessionUtils {

    private MicroSessionUtils(){}

    private static final Gson GSON = new Gson();

    private static Logger log = LoggerFactory.getLogger(MicroSessionUtils.class);

    /**
     * 通过code转换session
     * @param appId 小程序id
     * @param secret 小程序秘钥
     * @param code 小程序获取的code
     * @return code换session的结果
     */
    public static MicroSession code2Session(String appId, String secret, String code){
        String url = MessageFormat.format(UrlConstant.CODE2SESSION_URL, appId, secret, code);
        // 获取数据
        try {
            String result = HttpUtils.getData(url);
            log.info("wechat micro code2session code:{} result:{}", code, result);
            return GSON.fromJson(result, MicroSession.class);
        } catch (Exception e) {
            throw new MicroSessionException(e);
        }
    }
}
